package n001;

public class _0130_SurroundedRegions {

    public void solve(char[][] board) {
        int rowLen = board.length;
        int colLen = board[0].length;
        // 结合dfs将与边界相连的 O 替换为 F
        for (int i = 0; i < colLen; i++) {
            // 第一行
            if (board[0][i] == 'O') {
                dfs(board, 0, i);
            }
            // 最后一行
            if (board[rowLen - 1][i] == 'O') {
                dfs(board, rowLen - 1, i);
            }
        }
        for (int i = 1; i < rowLen - 1; i++) {
            // 第一列
            if (board[i][0] == 'O') {
                dfs(board, i, 0);
            }
            // 最后一列
            if (board[i][colLen - 1] == 'O') {
                dfs(board, i, colLen - 1);
            }
        }


        for (int i = 0, boardLength = board.length; i < boardLength; i++) {
            char[] row = board[i];
            for (int j = 0, rowLength = row.length; j < rowLength; j++) {
                // 将所有不与边界相连的 O 换为 X
                if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                } else if (board[i][j] == 'F') {
                    board[i][j] = 'O';
                }
            }
        }

    }

    public void dfs(char[][] board, int i, int j) {

        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != 'O') {
            return;
        }

        board[i][j] = 'F';
        dfs(board, i - 1, j);
        dfs(board, i + 1, j);
        dfs(board, i, j - 1);
        dfs(board, i, j + 1);
    }

}
